<template>
  <div class="article-list">
    <van-pull-refresh
      v-model="isRefreshLoading"
      @refresh="onRefresh"
    ><template slot="success">
        {{refreshText}}
      </template>
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <article-item
          v-for="(item,index) in list"
          :key="index"
          :article="item"
        ></article-item>
      </van-list>
    </van-pull-refresh>

  </div>
</template>

<script>
import { getUserArticle } from '@/api/article.js'
import ArticleItem from '@/components/article-item.vue'
export default {
  name: 'ArticleList',
  props: {
    channel: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      timestamp: null,
      isRefreshLoading: false,
      refreshText: null
    }
  },
  computed: {},
  watch: {},
  created () { },
  mounted () { },
  methods: {
    async  onLoad () {
      try {
        const { data: res } = await getUserArticle({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now(),
          with_top: 1
        })
        console.log(res)
        this.list.push(...res.data.results)
        this.timestamp = res.data.pre_timestamp
        // 加载状态结束
        this.loading = false
        // 数据全部加载完成
        if (res.data.results.length === 0) {
          this.finished = true
        }
      } catch (err) {
        this.finished = true
        this.loading = false
      }
    },
    async  onRefresh () {
      try {
        const { data: res } = await getUserArticle({
          channel_id: this.channel.id,
          timestamp: Date.now(),
          with_top: 1
        })
        this.refreshText = `刷新成功，获得${res.data.results.length}条数据`
        this.list.unshift(...res.data.results)
        this.isRefreshLoading = false
      } catch (err) {
        this.isRefreshLoading = false
        this.refreshText = '刷新失败'
      }
    }
  },
  components: {
    ArticleItem
  }
}
</script>

<style scoped lang="less">
.article-list {
  position: fixed;
  top: 180px;
  bottom: 100px;
  right: 0;
  left: 0;
  overflow-y: auto;
}
</style>
